package com.yuyou.fn.datadeal.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.crm.service.ICrmCommunicateHistoryService;
import com.yuyou.fn.crm.service.ICrmStudentCommunicateService;
import com.yuyou.fn.crm.service.ICustomerResourceService;
import com.yuyou.fn.datadeal.entity.RecordMergeStudent;
import com.yuyou.fn.datadeal.service.IRecordMergeStudentService;
import com.yuyou.fn.datadeal.service.IStudentMergeService;
import com.yuyou.fn.educational.entity.Student;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.report.service.IMergeStudentRegDetailService;
import com.yuyou.fn.settlement.entity.MainAccount;
import com.yuyou.fn.settlement.service.IMainAccountService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * ApplyClass 表数据服务层接口
 *
 */
@Service
public class StudentMergeServiceImpl  implements IStudentMergeService{

    /*记录可以直接替换的 studentId的table*/
    public static List<String> changeStudentIdTable =new ArrayList<>();

    /*记录可以直接替换的 mainAccountId 的table*/
    public static List<String> changeMainAccountIdTable=new ArrayList<>();

    /*删除student_id 为 originStudentId 的table */
    public static List<String> deleteStudentIdTable=new ArrayList<>();

    @Resource
    DataSource dataSource;


    @Resource
    private IStudentService studentService;

    @Resource
    private ICustomerBindStudentService customerBindStudentService;

    @Resource
    private IMainAccountService mainAccountService;

    @Resource
    private IRecordMergeStudentService recordMergeStudentService;

    @Resource
    private IOnlineTestService onlineTestService;

    @Resource
    private IMergeStudentRegDetailService mergeStudentRegDetailService;


    static {
        changeStudentIdTable.add("attend_class_record");
        changeStudentIdTable.add("change_class");
        changeStudentIdTable.add("course_order");
        changeStudentIdTable.add("crm_communicate_history");
        changeStudentIdTable.add("crm_customer_resource");
        changeStudentIdTable.add("crm_visit");
        changeStudentIdTable.add("degree_lock_record");
        changeStudentIdTable.add("external_measure_score");
        changeStudentIdTable.add("external_reg_detail");
        changeStudentIdTable.add("shift_class_record");
        changeStudentIdTable.add("student_guardian");
        changeStudentIdTable.add("student_measure_score");
        changeStudentIdTable.add("student_refund");
        changeStudentIdTable.add("student_reg");
        changeStudentIdTable.add("tms_balance_transfer");

        deleteStudentIdTable.add("crm_student_communicate");

        changeMainAccountIdTable.add("withdrawal");
        changeMainAccountIdTable.add("account_recharge");
        changeMainAccountIdTable.add("balance_change");
        changeMainAccountIdTable.add("balance_lock_record");
        changeMainAccountIdTable.add("change_record");
    }


    @Override
    @Transactional
    public void mergeStudentToAnother(long originStudentId, long targetStudentId,String cid) throws SQLException {
        Statement statement = null ;
        Connection connection=null;
        try {
            connection = DataSourceUtils.getConnection(dataSource);;
            statement = connection.createStatement();

            for (String table : changeStudentIdTable) {
                statement.addBatch("update " + table + " set student_id = " + targetStudentId + ",update_time=NOW() where student_id = " + originStudentId );
            }

            for (String table:deleteStudentIdTable){
                statement.addBatch("DELETE FROM "+ table+ " where student_id =" +originStudentId);
            }

            for (String table : changeMainAccountIdTable) {
                statement.addBatch("update " + table + " set main_account_id = " + targetStudentId + ", update_time=NOW() where main_account_id = " + originStudentId);
            }

            statement.executeBatch();
            RecordMergeStudent recordMergeStudent=new RecordMergeStudent();
            recordMergeStudent.setCreateTime(TimeUtils.now());
            recordMergeStudent.setUpdateTime(TimeUtils.now());
            recordMergeStudent.setOriginStudentId(originStudentId);
            recordMergeStudent.setTargetStudentId(targetStudentId);
            recordMergeStudentService.insert(recordMergeStudent);
            customerBindStudentService.mergeBindByOriginAndTargetStudentId(originStudentId,targetStudentId);
            mainAccountService.mergeAmountByOriginAndTargetStudentId(originStudentId,targetStudentId);
            studentService.mergeStudentByOriginAndTargetStudentId(originStudentId,targetStudentId,cid);
            onlineTestService.mergeOnlineTest(originStudentId,targetStudentId);
            mergeStudentRegDetailService.deleteByStudentId(originStudentId);

        }catch (Exception e){
            throw new BusException("更新失败",e);
        }

    }


    public String resultSetToJson(ResultSet rs) throws SQLException, JSONException {
        // json数组
        JSONArray array = new JSONArray();

        // 获取列数
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();

        // 遍历ResultSet中的每条数据
        while (rs.next()) {
            JSONObject jsonObj = new JSONObject();

            // 遍历每一列
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnLabel(i);
                String value = rs.getString(columnName);
                jsonObj.put(columnName, value);
            }
            array.add(jsonObj);
        }
        return array.toString();
    }




}